//
//  BudgetPieCollectionView.m
//  BaseProject
//
//  Created by mac on 2020/10/28.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "BudgetPieCollectionView.h"

@interface BudgetPieCollectionCell : UIView
@property(nonatomic,strong)BudgetPieItemModel *itemModel;
@property(nonatomic,strong)UILabel *titleLab;
@property(nonatomic,strong)UIView *colorView;
@end

@implementation BudgetPieCollectionCell
- (void)setItemModel:(BudgetPieItemModel *)itemModel
{
    _itemModel = itemModel;
    self.titleLab.text = [NSString stringWithFormat:@"%@ %0.2f%c",itemModel.title,itemModel.percent * 100,'%'];
    self.colorView.backgroundColor = itemModel.color;
}
#pragma mark - lazy懒加载
- (UILabel *)titleLab
{
    if (!_titleLab) {
        UILabel *lab = [[UILabel alloc]init];
        [self addSubview:lab];
        lab.font = [UIFont systemFontOfSize:9*ADAPTER_WIDTH weight:UIFontWeightRegular];
        lab.textColor = RGB(51, 51, 51);
        lab.textAlignment = NSTextAlignmentLeft;
        lab.numberOfLines = 1;
        lab.frame = CGRectMake(0, 10*ADAPTER_WIDTH, self.width, 11*ADAPTER_WIDTH);
        _titleLab = lab;
    }
    return _titleLab;
}
- (UIView *)colorView
{
    if (!_colorView) {
        UIView *view = [[UIView alloc]init];
        view.frame = CGRectMake(self.width - 25*ADAPTER_WIDTH, 0, 15*ADAPTER_WIDTH, 15*ADAPTER_WIDTH);
        view.centerY = self.titleLab.centerY;
        [self addSubview:view];
        _colorView = view;
    }
    return _colorView;
}
@end

@interface BudgetPieCollectionView ()
@property(nonatomic,strong)NSMutableArray *itemsArray;
@end

@implementation BudgetPieCollectionView
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}
- (void)setDataSource:(NSMutableArray<BudgetPieItemModel *> *)dataSource
{
    _dataSource = dataSource;
    [self.itemsArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    [self.itemsArray removeAllObjects];
    
    CGFloat orinY = 0,marignX = 10*ADAPTER_WIDTH,itemWidth = (self.width - 2 * marignX) / 3,itemHeight = 40*ADAPTER_WIDTH;
    for (NSInteger index = 0; index < dataSource.count; index ++) {
        BudgetPieCollectionCell *cell = [[BudgetPieCollectionCell alloc]initWithFrame:CGRectMake((index % 3) * itemWidth + marignX, (index / 3) * itemHeight, itemWidth, itemHeight)];
        [self addSubview:cell];
        cell.itemModel = dataSource[index];
        [self.itemsArray addObject:cell];
        orinY = cell.bottom;
    }
    self.height = orinY;
}
#pragma mark - lazy懒加载
- (NSMutableArray *)itemsArray
{
    if (!_itemsArray) {
        _itemsArray = [NSMutableArray array];
    }
    return _itemsArray;
}
@end
